package cn.conac.as.gateway.app.rest;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.conac.as.framework.utils.FastJsonUtil;
import cn.conac.as.framework.utils.IdGen;
import cn.conac.as.framework.utils.ResultPojo;
import cn.conac.as.framework.utils.StringUtils;
import cn.conac.as.gateway.app.entity.BdtCollectionEntity;
import cn.conac.as.gateway.app.entity.BdtLawClsIdxEntity;
import cn.conac.as.gateway.app.entity.BdtLawContentEntity;
import cn.conac.as.gateway.app.service.AppLawDBService;
import cn.conac.as.gateway.app.service.AppLawService;
import cn.conac.as.gateway.app.utils.PropertiesUtil;
import cn.conac.as.gateway.app.vo.BdtCollectionVo;
import cn.conac.as.gateway.app.vo.BdtLawSrhVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

//import cn.conac.as.framework.utils.StringUtils;

@RestController
@Api(tags = "Law-Gateway", description = "包打听——法律法规相关接口")
@RequestMapping(value="bdt/law/")
public class AppLawController {

	/**
	 * AppLawService(北大法宝接口用Service)
	 */
	@Autowired
	private AppLawService appLawService;

	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;

	/**
	 * 文件配置路径(系统路径)
	 */
	@Value("${file.server.path}")
	private String serverPath;
	/**
	 * 文件配置路径(系统路径)
	 */
	@Value("${file.server.number}")
	private String number;
	/**
	 * 文件访问路径(访问路径)
	 */
	@Value("${file.server.address}")
	private String address;


	/**
	 * AppLawDBService(本地数据库操作用Service)
	 */
	@Autowired
	private AppLawDBService appLawDBService;
	@ApiOperation(value = "根据效力级别从本地获取数据，显示法律法规首页", httpMethod = "GET", notes = "根据效力级别从本地获取数据，显示法律法规首页")
	@RequestMapping(value = "list/{effectivenessDic}/{rowNum}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<ResultPojo> homePageShowLogic(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "effectivenessDic", required = true) @PathVariable("effectivenessDic") String effectivenessDic,
			@ApiParam(value = "rowNum", required = true) @PathVariable("rowNum") String rowNum)
			throws Exception {

		// 返回结果声明
		ResultPojo result = new ResultPojo();

		// 链接本地接口，获取JSON数据
		JSONObject rtlJson = appLawDBService.findByEffectivenessDicAndRowNum(effectivenessDic,rowNum);
		JSONArray jsonArray = rtlJson.getJSONArray("result");

		// 结果设定
		result.setResult(jsonArray);

		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@ApiOperation(value = "数据筛选【SSSX】", httpMethod = "POST", notes = "用于法律法规筛选")
	@RequestMapping(value = "sssx", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<ResultPojo> shuJuShaXuan(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "查询条件对象", required = true) @RequestBody JSONObject sssxVo)
			throws Exception {

		// 返回结果声明
		ResultPojo result = new ResultPojo();
		List<BdtLawClsIdxEntity> list = new ArrayList<BdtLawClsIdxEntity>();
		// 设置检索对象
		BdtLawSrhVo bdtLawSrhVo = JSONObject.toJavaObject(sssxVo, BdtLawSrhVo.class);
		// 链接北大法宝接口，获取JSON数据
		JSONObject sssxJson = appLawService.shuJuShaXuan(bdtLawSrhVo);
		// 与北大法宝接口断裂时，再次访问本地数据库检索
		if(sssxJson == null || "null".equals(sssxJson)){
			JSONObject ssssxDBJson = appLawDBService.findBdtLawClsIdxList(bdtLawSrhVo);
			JSONArray jArray = ssssxDBJson.getJSONObject("result").getJSONArray("content");
			for(int i=0; i<jArray.size(); i++){
				BdtLawClsIdxEntity blciEntity = JSONObject.toJavaObject(jArray.getJSONObject(i),BdtLawClsIdxEntity.class);
				list.add(blciEntity);
			}
			// 未断裂时，显示北大接口出来的数据
		} else {
			JSONArray jArray = sssxJson.getJSONObject("Data").getJSONArray("Collection");
			int pageCount = Integer.parseInt(sssxJson.getJSONObject("Data").getString("PageCount"));
			int pageIndex = Integer.parseInt(sssxVo.getString("pageIndex"));
			// 如果翻页后，还有数据则显示数据，没有则显示为空
			if(pageCount>=pageIndex+1){
				for(int i=0; i<jArray.size(); i++){
					JSONObject jsonObject = jArray.getJSONObject(i);
					BdtLawClsIdxEntity blciEntity = new BdtLawClsIdxEntity();
					blciEntity.setTitle(jsonObject.getString("Title"));// 法规标题
					blciEntity.setDocumentNo(StringUtils.insteadWithNone(jsonObject.getString("DocumentNO")));// 发文字号
					blciEntity.setIssueDepartment(FastJsonUtil.getJSONValue(jsonObject.getJSONObject("IssueDepartment")));// 发布部门
					blciEntity.setIssueDate(StringUtils.insteadWithNone(jsonObject.getString("IssueDate")));// 发布日期
					blciEntity.setEffectivenessDic(FastJsonUtil.getJSONKey(jsonObject.getJSONObject("EffectivenessDic")).substring(0,4));// 效力级别CD
					// blciVo.setEffectiveness(jsonObject.getJSONObject("Effectiveness").getString("Value"));// 效力级别NAME
					blciEntity.setEffectiveness(appLawDBService.findByClsCode12("EffectivenessDic",blciEntity.getEffectivenessDic()).getJSONObject("result").getString("clsName2"));// 效力级别NAME
					blciEntity.setCategory(FastJsonUtil.getJSONValue(jsonObject.getJSONObject("Category")));// 法规类别
					blciEntity.setTimelinessDic(FastJsonUtil.getJSONKey(jsonObject.getJSONObject("TimelinessDic")));// 时效性CD
					blciEntity.setTimeliness(FastJsonUtil.getJSONValue(jsonObject.getJSONObject("TimelinessDic")));// 时效性NAME
					blciEntity.setImplementDate(jsonObject.getString("ImplementDate"));// 实施日期
					blciEntity.setRevisedBasis(jsonObject.getString("RevisedBasis"));// 修改依据
					blciEntity.setPartialFailureBasis(jsonObject.getString("PartialFailureBasis"));// 部分失效依据
					blciEntity.setFailureBasis(jsonObject.getString("FailureBasis"));//
//					list.add(blciEntity);//原来的
					//更改2017年6月17日
					JSONObject bdtResult =
							appLawDBService.findBdtLawClsIdxByTitleAndDocNoAndIssueDate(blciEntity);
					if(bdtResult.get("result")==null){
						String id = IdGen.uuid();
						blciEntity.setId(id);
						appLawDBService.savOrUpdBdtLawClsIdx(blciEntity);
						BdtLawSrhVo blsVo = new BdtLawSrhVo();
						// 调用数据检索接口
						blsVo.setTitle(jsonObject.getString("Title"));// 法规标题
						blsVo.setDocumentNo(jsonObject.getString("DocumentNO"));// 发文字号
						JSONObject ssjsJsonObj = appLawService.shuJuJianSuo(blsVo);

						// 如果未查到数据【没有找到此篇法规】，则不留存
						String fullText = ssjsJsonObj.getString("Data");

						// 追加本地DB--法律法规内容表
						BdtLawContentEntity blcEntity = new BdtLawContentEntity();
						blcEntity.setId(id);
						blcEntity.setTitle(jsonObject.getString("Title"));// 法规标题
						blcEntity.setFullText(StringUtils.dealWithFullText(fullText));// 全文
						blcEntity.setRatifyDepartment(FastJsonUtil.getJSONValue(jsonObject.getJSONObject("RatifyDepartment")));// 批准部门
						blcEntity.setRatifyDate(jsonObject.getString("RatifyDate"));// 批准日期
						appLawDBService.savOrUpdBdtLawContent(blcEntity);
						list.add(blciEntity);
					}else{
						JSONObject bdtResultJson = bdtResult.getJSONObject("result");
						BdtLawClsIdxEntity bdtResultVo = bdtResultJson.toJavaObject(BdtLawClsIdxEntity.class);
						list.add(bdtResultVo);
					}//
				}
			}
		}

		// 结果设定
		result.setResult(list);

		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@ApiOperation(value = "数据检索【SSJS】", httpMethod = "POST", notes = "用于法律法规数据检索")
	@RequestMapping(value = "ssjs", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<ResultPojo> shuJuJianSuo(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "查询条件对象", required = true) @RequestBody JSONObject ssjsVo)
			throws Exception {
		// 返回结果声明
		ResultPojo result = new ResultPojo();

		// 去除标题中带有格式的内容
		String title = StringUtils.removeHtmlfromTitle(ssjsVo.getString("title"));

		// 检索本地DB，获取JSON数据
		BdtLawClsIdxEntity srchEntity = new BdtLawClsIdxEntity();
		srchEntity.setTitle(title);
		srchEntity.setDocumentNo(StringUtils.insteadWithNone(ssjsVo.getString("documentNo")));
		srchEntity.setIssueDate(StringUtils.insteadWithNone(ssjsVo.getString("issueDate")));
		JSONObject checkRtl = appLawDBService.findBdtLawClsIdxByTitleAndDocNoAndIssueDate(srchEntity);

		// 判断是否已经留存
		String checkCode = checkRtl.getString("code");
		// 已经留存时，只显示
		if(ResultPojo.CODE_SUCCESS.equals(checkCode)){
			JSONObject rtl = appLawDBService.findBdtLawContentById(checkRtl.getJSONObject("result").getString("id"));
			result.setResult(rtl.getJSONObject("result").getString("fullText"));
			// 未留存时，链接北大法宝接口，并且留存数据
		} else {
			// 去除标题中带有格式的内容
			BdtLawSrhVo blsVo = JSONObject.toJavaObject(ssjsVo, BdtLawSrhVo.class);
			blsVo.setTitle(title);

			// 链接北大法宝接口，获取JSON数据
			JSONObject ssjsJson = appLawService.shuJuJianSuo(blsVo);
			String rtl = StringUtils.dealWithFullText(ssjsJson.getString("Data"));
			result.setResult(rtl);

			// 如果未查到数据【没有找到此篇法规】，则不留存
			if("没有找到此篇法规".equals(StringUtils.trim(rtl))){
				// do nothing
			} else {
				// 数据留存
				String id = IdGen.uuid();// 获取主键

				BdtLawClsIdxEntity blciEntity = JSONObject.toJavaObject(ssjsVo, BdtLawClsIdxEntity.class);
				blciEntity.setId(id);
				blciEntity.setTitle(title);// 标题
				appLawDBService.savOrUpdBdtLawClsIdx(blciEntity);

				BdtLawContentEntity blcEntity = JSONObject.toJavaObject(ssjsVo, BdtLawContentEntity.class);
				blcEntity.setId(id);
				blcEntity.setTitle(title);//标题
				blcEntity.setRatifyDepartment(FastJsonUtil.getJSONValue(ssjsVo.getJSONObject("RatifyDepartment")));// 批准部门
				blcEntity.setRatifyDate(ssjsVo.getString("RatifyDate"));// 批准日期
				blcEntity.setFullText(rtl);// 全文
				appLawDBService.savOrUpdBdtLawContent(blcEntity);
			}
		}

		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@ApiOperation(value = "根据一级分类CD获取分类列表", httpMethod = "GET", notes = "根据一级分类CD获取分类列表")
	@RequestMapping(value = "dic/{clsCode1}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<ResultPojo> findByClsCode1(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "clsCode1", required = true) @PathVariable("clsCode1") String clsCode1)
			throws Exception {

		// 返回结果声明
		ResultPojo result = new ResultPojo();

		// 链接本地接口，获取JSON数据
		JSONObject rtlJson = appLawDBService.findByClsCode1(clsCode1);

		// 结果设定
		result.setResult(rtlJson.getJSONArray("result"));

		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	/**
	 * 根据法律法规id返回静态页面
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "静态页面", httpMethod = "GET", notes = "用于返回静态页面")
	@RequestMapping(value = "ssjs/{id}", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo>  freeMarkUrl(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "法律法规ID", required = true)@PathVariable String id)
			throws Exception {
		// 返回结果声明
		ResultPojo result = new ResultPojo();
		JSONObject bdtLawContent = appLawDBService.findBdtLawContentById(id);
		JSONObject bdtLawClsIdx = appLawDBService.findbdtLawClsIdxById(id);

		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		Template template = configuration.getTemplate("hello.ftl");
		Map data=new HashMap<>();

		BdtLawContentEntity bdtLawContentVo = JSONObject.toJavaObject(bdtLawContent.getJSONObject("result"), BdtLawContentEntity.class);
		BdtLawClsIdxEntity bdtLawClsIdxVo = JSONObject.toJavaObject(bdtLawClsIdx.getJSONObject("result"), BdtLawClsIdxEntity.class);

		String urlPath = bdtLawClsIdxVo.getUrlPath();
		String revisedBasis = bdtLawClsIdxVo.getRevisedBasis();
		String realPath = number;
		if (urlPath==null || revisedBasis != null){
			data.put("bdtLawContent",bdtLawContentVo);
			data.put("bdtLawClsIdx",bdtLawClsIdxVo);
			File file = new File(serverPath+"/"+number);
			if(!file.exists()){
				file.mkdirs();
			}
			File[] files = file.listFiles();
			if (files.length>10000){
				int i = Integer.valueOf(number) + (int) 1;
				number=String.valueOf(i);
				PropertiesUtil.setProper("file.server.number",number);
				new File(serverPath+"/"+number).mkdirs();
				realPath=number;
			}
			System.out.println("页面路径"+serverPath+realPath+"/"+id+".html");

			Writer out = new FileWriter(new File(serverPath+realPath+"/"+id+".html"));
			template.process(data,out);
			out.close();
			bdtLawClsIdxVo.setUrlPath(realPath+"/"+id+".html");
			String s = bdtLawClsIdxVo.getUrlPath();
			appLawDBService.savOrUpdBdtLawClsIdx(bdtLawClsIdxVo);

			result.setResult(address+"html/"+realPath+"/"+id+".html");
			return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
		}
		result.setResult(address+"html/"+urlPath);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	/**
	 * 根据客户端类型、版本号和法律法规id返回静态页面 2017年6月8日
	 * @param request
	 * @param response
	 * @param clientType
	 * @param versionId
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "静态页面", httpMethod = "GET", notes = "根据客户端类型和版本号返回静态页面")
	@RequestMapping(value = "ssjs/{clientType}/{versionId}/{id}", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo>  freeMarkUrl(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "客户端类型", required = true)@PathVariable String clientType,@ApiParam(value = "版本号", required = true)@PathVariable String versionId,@ApiParam(value = "法律法规ID", required = true)@PathVariable String id)
			throws Exception {
		// 返回结果声明
		ResultPojo result = new ResultPojo();
		JSONObject bdtLawContent = appLawDBService.findBdtLawContentById(id);
		JSONObject bdtLawClsIdx = appLawDBService.findbdtLawClsIdxById(id);

		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		Template template = configuration.getTemplate("hello.ftl");
		Map data=new HashMap<>();

		BdtLawContentEntity bdtLawContentVo = JSONObject.toJavaObject(bdtLawContent.getJSONObject("result"), BdtLawContentEntity.class);
		BdtLawClsIdxEntity bdtLawClsIdxVo = JSONObject.toJavaObject(bdtLawClsIdx.getJSONObject("result"), BdtLawClsIdxEntity.class);

		String urlPath = bdtLawClsIdxVo.getUrlPath();
		String revisedBasis = bdtLawClsIdxVo.getRevisedBasis();
		String realPath = number;
		if (urlPath==null || revisedBasis != null){
			data.put("bdtLawContent",bdtLawContentVo);
			data.put("bdtLawClsIdx",bdtLawClsIdxVo);
			File file = new File(serverPath+"/"+number);
			if(!file.exists()){
				file.mkdirs();
			}
			File[] files = file.listFiles();
			if (files.length>10000){
				int i = Integer.valueOf(number) + (int) 1;
				number=String.valueOf(i);
				PropertiesUtil.setProper("file.server.number",number);
				new File(serverPath+"/"+number).mkdirs();
				realPath=number;
			}
			System.out.println("页面路径"+serverPath+realPath+"/"+id+".html");

			Writer out = new FileWriter(new File(serverPath+realPath+"/"+id+".html"));
			template.process(data,out);
			out.close();
			bdtLawClsIdxVo.setUrlPath(realPath+"/"+id+".html");
			String s = bdtLawClsIdxVo.getUrlPath();
			appLawDBService.savOrUpdBdtLawClsIdx(bdtLawClsIdxVo);

			result.setResult(address+"html/"+realPath+"/"+id+".html");
			return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
		}
		result.setResult(address+"html/"+urlPath);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@RequestMapping(value = "collection", method = RequestMethod.POST)
	public ResponseEntity<ResultPojo> saveCollection(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "收藏的内容", required = true) @RequestBody JSONObject collectionVo){

		ResultPojo result = new ResultPojo();
		BdtCollectionEntity colletctionEntity = new BdtCollectionEntity();
		String id = IdGen.uuid();
		colletctionEntity.setId(id);
		colletctionEntity.setContentPath(StringUtils.insteadWithNone(collectionVo.getString("contentPath")));
		colletctionEntity.setContentTitle(StringUtils.insteadWithNone(collectionVo.getString("contentTitle")));
		colletctionEntity.setUserId(StringUtils.insteadWithNone(collectionVo.getString("userId")));
		colletctionEntity.setTypeId(StringUtils.insteadWithNone(collectionVo.getString("typeId")));
		colletctionEntity.setTypeName(StringUtils.insteadWithNone(collectionVo.getString("typeName")));
		colletctionEntity.setCreateDate(new Date());
		BdtCollectionVo bdtCollectionVo = collectionVo.toJavaObject(BdtCollectionVo.class);
		bdtCollectionVo.setPageIndex(0);
		bdtCollectionVo.setPageSize(1);
		JSONObject bdtCollection = appLawDBService.findBdtCollection(bdtCollectionVo);
		JSONArray jsonArray = bdtCollection.getJSONObject("result").getJSONArray("content");
		if(jsonArray.size()>0){
			result.setMsg("已收藏");
		}else{
			JSONObject rtlJson = appLawDBService.savOrUpdBdtCollection(colletctionEntity);
			result.setResult("收藏成功");
		}

		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@RequestMapping(value = "collection/{userid}/{pageindex}/{pagesize}", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> findCollectionByUserid(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "用户id", required = true) @PathVariable("userid") String userid,@ApiParam(value = "当前页数") @PathVariable("pageindex") Integer pageindex,@ApiParam(value = "每页显示条数") @PathVariable("pagesize") Integer pagesize){

		ResultPojo result = new ResultPojo();
		List<BdtCollectionEntity> list = new ArrayList<>();
		BdtCollectionVo collectionVo = new BdtCollectionVo();
		collectionVo.setUserId(userid);

		collectionVo.setPageIndex(pageindex==null ? 0:pageindex);
		collectionVo.setPageSize(pagesize==null ? 10:pagesize);
		JSONObject rtlJson = appLawDBService.findBdtCollection(collectionVo);
		JSONArray jArray = rtlJson.getJSONObject("result").getJSONArray("content");


		for (int i=0;i<jArray.size();i++){
			BdtCollectionEntity collectionEntity =
					JSONObject.toJavaObject(jArray.getJSONObject(i), BdtCollectionEntity.class);
			list.add(collectionEntity);
		}


		result.setResult(list);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@RequestMapping(value = "collection/{id}/delete", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> deleteById(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "ID", required = true) @PathVariable("id") String id ){

		ResultPojo result = new ResultPojo();
		appLawDBService.deleteById(id);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

}
